package com.yyge.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

// swagger 配置类
@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {
    //配置Swagger2的Docket的Bean实例
    @Bean
    public Docket createRestApi() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.any())
                .build();
        //设置模拟请求时的鉴权方式:在header中携带Authorization
        docket.securitySchemes(Collections.singletonList(new ApiKey("Authorization",
                "Authorization", "header")));
        SecurityReference reference =
                new SecurityReference("Authorization",
                        new AuthorizationScope[] {new AuthorizationScope("global","accessEverything")});
        List<SecurityReference> refList = new ArrayList<>();
        refList.add(reference);
        SecurityContext context = SecurityContext.builder().securityReferences(refList).build();
        List<SecurityContext> cxtList = new ArrayList<>();
        cxtList.add(context);
        docket.securityContexts(cxtList);
        return docket;
    }

    /**
     * Swagger 基本信息
     * @return ApiInfo
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .contact(new Contact("gityyge", "主页地址", "邮箱"))
                .title("Spring").description("项目描述")
                .version("1.0")
                .build();
    }
}

